<template>
    <div>

        <el-main v-if="headBtn===undefined">
            <el-button type="primary" style="margin-left:10px;" @click="myClickEvent(null,-1,'新增')">新增</el-button>
            <el-button type="warning" v-show="mySelection.length>0" @click="myClickEvent(null,-1,'批量删除')">批量删除</el-button>
        </el-main>

        <el-table :data="content" @select="mySelectEvent" @select-all="mySelectEvent">
            <el-table-column v-if="typeBefore==undefined" type="index" width="80px;"/>
            <el-table-column v-else v-for="(typeName) in typeBefore" v-bind:type="typeName" width="80px;"/>

            <el-table-column v-for="(headItm) in tableHeadJsonArray" :property="headItm.colName" :label="headItm.showName">
                <template slot-scope="scope">
                    <p v-if="headItm.colName==='isEnabled'">{{scope.row.isEnabled===1?'审核通过':'需要审核'}}</p>
                    <p v-else-if="headItm.isJson===true">
                        <!-- 如果要在一个嵌套的jsonObject中取得数据，把 isJson指定为true，并在getCol中指明要读取的数据字段，否则默认使用name -->
                        <!--{{scope.row[headItm.colName][(headItm.getCol===undefined)?'name':headItm.getCol]}}-->
                        {{getText(scope.row,headItm.colName,headItm.getCol)}}
                    </p>
                    <p v-else>{{scope.row[headItm.colName]|removeHtmlTag}}</p>
                </template>
            </el-table-column>

            <el-table-column label="操作">
                <template scope="scope">
                    <!-- 重要数据 scope.$index, scope.row -->
                    <div class="row">
                        <button v-for="(operation) in additionBtns" :class="operation.myStyle" @click="myClickEvent(scope.row,scope.$index,operation.name)">{{operation.name}}</button>
                    </div>
                </template>
            </el-table-column>

        </el-table>

        <div class="Pagination" style="text-align: left;margin-top: 10px;">
            <el-pagination :current-page="currentPage" :page-size="pageSize" layout="total, prev, pager, next" :total="totalCount"
                           @current-change="switchPage" :page-count="pageCount"/>
        </div>

        <el-dialog v-bind:title="myModelTitle" :visible.sync="myModelVisibility">
            <el-form>
                <el-form-item v-for="(itm,idx) in myModelContent" v-bind:label="itm.name">
                    <!--<el-input @input.native="$event.$forceUpdate()" style="display:inline-block;width:33%;" v-model="itm.value"></el-input>-->
                    <input class="input-group-text" v-if="!itm.webform" style="background-color:white;display:inline-block;width:33%;" v-model="itm.value"></input>
                    <Web_fill_input v-if="itm.webform" :get-name="itm.getName" :data-u-r-l="itm.from" v-model="itm.value" style="background-color:white;display:inline-block;width:33%;"></Web_fill_input>
                </el-form-item>
            </el-form>
            <span slot="footer">
            <el-button type="primary" @click.native="modelConfirmed">确定</el-button>
            <el-button @click.native="myModelVisibility = false">取消</el-button>
        </span>
        </el-dialog>

    </div>
</template>

<script>
    import axios from 'axios'
    import Web_fill_input from "./Web_fill_input";
    export default {
        name: "Result_form",
        components: {Web_fill_input},
        props:['typeBefore','tableHeadJsonArray','additionBtns','requestURL','opBaseUrl','headBtn'],
        //typeBefore 字符串数组，表示加在表头前的特殊列的类型，如['index','selection']
        //tableHeadJsonArray 表头数组，应当指定列名（数据库的列明）和显示名（对应注释） 如 [{colName:'sNo',showName:'学号'}]
        //additionBtns 提供额外选项的按钮，需要指定名称和样式 [{myStyle:'btn btn-primary',name:'查看详情'}] ,单击事件由父容器处理
        //requestURL 查询链接

        //resultJsonArray 直接存放查询结果，仅用于兼容以前的设计，并将在后期移除此参数，请勿再用

        data(){
            return {
                content:[],
                currentPage:1,
                pageSize:10,
                totalCount:0,
                pageCount:0,
                mySelection:[],
                myModelVisibility:false,
                myModelData:[],
                myModelContent:[],
                myModelTitle:''
            }
        },
        methods:{
            dialogWebForm(text,id,formName,select){
                console.log(text)
                console.log(id)
                console.log(formName)
                console.log(select)
            },
            getText(currentRow,colName,getCol){
                // {{scope.row[headItm.colName][(headItm.getCol===undefined)?'name':headItm.getCol]}}
                if(getCol===undefined) return currentRow[colName].name;
                else{
                    let tmpValue = currentRow[colName]
                    for(let i=0;i<getCol.length;i++){
                        tmpValue = tmpValue[getCol[i]]
                    }
                    return tmpValue;
                }
            },
            modelConfirmed(){
                console.log(this.myModelData)
                this.myModelVisibility = false
                if(this.myModelTitle==='新增'){
                    const params2 = new URLSearchParams();
                    let params = {}

                    this.myModelContent.forEach((item)=>{
                        params[item.id] = item.value;
                        params2.append(item.id, item.value);
                    })

                    axios.post(this.opBaseUrl + '/add',params2).then(e=>{
                        let success = false;
                        // console.log(e)
                        if(!(success = e.data.succeed)){
                            // console.error("添加失败，更换参数格式")
                            axios.post(this.opBaseUrl + '/add',params).then(e=>{
                                console.log(e)
                                success = e.data.succeed
                            })
                        }
                        if(success) alert('操作成功')
                        else alert('操作失败')
                    })
                }
            },
            mySelectEvent(e){
                this.$emit('rowSelected',e)
                this.mySelection = e;
            },
            myClickEvent(currentRow,rowId,operation){
                this.$emit('rowClicked',currentRow,rowId,operation)
                // console.log(currentRow)
                // console.warn(rowId + operation)
                if(operation==='新增'){
                    this.myModelVisibility = true
                    this.myModelContent = this.ito;
                    this.myModelTitle = '新增'
                }
                if(operation==='查看'){
                    this.myModelVisibility = true
                    this.myModelData = currentRow;
                    this.myModelContent = this.itn;
                    this.myModelTitle = '详情'
                }
                if(operation==='删除'){
                    let is_ok = confirm("确定要删除本项吗？")
                    if(is_ok) {
                        this.content.splice(rowId, 1);
                    }
                }
                if(operation==='批量删除'){
                    let is_ok = confirm('确定批量删除所选的' + this.mySelection.length + '项吗？')
                    for(let i=0;i<this.content.length;i++){
                        if(this.mySelection.indexOf(this.content[i])!==-1){
                            console.error('当前仅在前端实现模拟删除，请在此处补充向后端发送的删除请求')
                            this.content.splice(i,1);
                            --i;
                        }
                    }
                    this.mySelection = [];
                }
                if(operation==='审核通过'){
                    let is_ok = confirm("确定要允许本单位入驻吗？")
                    if(is_ok){
                        this.content[rowId].isEnabled=1
                        axios.get(this.opBaseUrl + '/unlock?id=' + currentRow.id);
                        //this.content.splice(rowId,1)
                    }
                }
                if(operation==='锁定'){
                    let is_ok = confirm("确定要将本单位锁定吗？")
                    if(is_ok){
                        this.content[rowId].isEnabled=0
                        axios.get(this.opBaseUrl + '/lock?id=' + currentRow.id).then(e=>{
                            console.log(e)
                        })
                        //this.content.splice(rowId,1)
                    }
                }

            },
            switchPage(newPage){
                this.currentPage = newPage
            }
        },
        filters:{
            removeHtmlTag(text){
                if(typeof(text)==="string"){
                    return text.replace(/<.*?>/ig,"")
                }else
                return text;
            }
        },
        mounted() {
            if(this.requestURL!==undefined&&this.requestURL!=='') {
                axios.get(this.requestURL).then(e => {
                    // console.log(e.data.data)
                    this.content = e.data.data.content
                    this.totalCount = e.data.data.count
                    this.pageCount = e.data.data.allPageNumber
                })
            }
        },
        watch:{
            currentPage(newPage,oldPage){
                let page_str = '&page=' + newPage + '&size=' + this.pageSize
                axios.get(this.requestURL + page_str).then(e=>{
                    // console.log(e.data.data)
                    this.content = e.data.data.content
                    this.totalCount = e.data.data.count
                    this.pageCount = e.data.data.allPageNumber
                })
            },
            pageSize(newSize,oldSize){
                let page_str = '&page=' + this.currentPage + '&size=' + newSize
                axios.get(this.requestURL + page_str).then(e=>{
                    // console.log(e.data.data)
                    this.content = e.data.data.content
                    this.totalCount = e.data.data.count
                    this.pageCount = e.data.data.allPageNumber
                })
            },
            requestURL(newURL,oldURL){
                //此处的article应该被修改为其他字段
                if(newURL!==''){
                    let page_str = '&page=' + this.currentPage + '&size=' + this.pageSize
                    axios.get(newURL + page_str).then(e=>{
                        // console.log('搜索结果：')
                        // console.log(e.data.data)
                        this.content = e.data.data.content
                        this.totalCount = e.data.data.count
                        this.pageCount = e.data.data.allPageNumber

                    })
                }
            }
        },
        computed:{
            ito(){
                let result = []
                let r = {};
                // console.log('进入计算')
                // console.error(this.content[0])
                // console.error(this.tableHeadJsonArray)
                for(let key in this.content[0]){
                    this.tableHeadJsonArray.forEach((item)=>{
                        if(item.inModel!==false&&item.colName === key){
                            r.value = ''
                            if(item.rename===undefined){
                                r.id = item.colName;
                            }else{
                                r.id = item.rename;
                                r.webform = true;
                                r.from = item.from
                            }
                            if(item.getName!==undefined){
                                r.getName = item.getName
                            }
                            r.name = item.showName;
                            result.push(r);
                            r = {};
                        }
                    })
                }
                //console.log(result)
                return result
            },
            itn(){
                //itn: [{name:'专业',value:'材料工程'}]
                let result = []
                let r = {};
                //console.log('进入计算')
                console.error(this.myModelData)
                console.error(this.tableHeadJsonArray)
                for(let key in this.myModelData){
                    this.tableHeadJsonArray.forEach((item)=>{

                        if(item.inModel!==false&&item.colName === key){
                            if(item.isJson===true){
                                //r.name =
                                if(item.getCol===undefined) {
                                    r.value = this.myModelData[key].name
                                }else{
                                    //r.value = this.myModelData[key][(item.getCol===undefined)?'name':item.getCol]
                                    let tmpValue = this.myModelData[key]
                                    //console.error(item.getCol)
                                    for(let i=0;i<item.getCol.length;i++){
                                        //console.warn('tmp:')
                                        //console.error(tmpValue)
                                        tmpValue = tmpValue[item.getCol[i]]
                                    }
                                    r.value = tmpValue;
                                }
                                //r.colName = item.rename===undefined?item.colName:item.rename;
                            }else {
                                r.value = this.myModelData[key];
                            }
                            r.id = item.rename===undefined?item.colName:item.rename;
                            r.name = item.showName;
                            result.push(r);
                            r = {};
                        }
                    })
                }
                //console.log(this.myModelData)
                //console.log(result)
                return result
            }
        }
    }
</script>

<style scoped>

</style>